import nodeResolve from '@rollup/plugin-node-resolve'
import typescript from "@rollup/plugin-typescript"
import commonjs from '@rollup/plugin-commonjs'
import postcss from "rollup-plugin-postcss"
import image from '@rollup/plugin-image'
import { join, resolve } from 'path'
import { readdir, unlink, rmdir, lstat } from 'fs/promises'
import { type RollupOptions, defineConfig } from 'rollup'
import { existsSync } from 'fs'
import babelMinify from 'rollup-plugin-babel-minify';

const commonPlugins = [
  typescript({
    tsconfig: "./tsconfig.json",
  }),
  commonjs(),
  postcss(),
  image(),
  nodeResolve(),
  babelMinify({
    removeConsole: true,
  }),
]
/**
 * @description 根据路径删除目录
 * @param dirs 删除的目录路径
 */
const removeDir = async (...dirs: string[]) => {
  for (const dir of dirs) {
    const absolutePath = resolve(__dirname, dir)
    if (existsSync(absolutePath)) {
      const dirStack = [absolutePath]
      while (dirStack.length > 0) {
        const initPath = dirStack[dirStack.length - 1]
        const fileStat = await lstat(initPath)
        if (fileStat.isDirectory()) {
          const files = await readdir(initPath)
          if (files.length > 0) {
            dirStack.push(...files.map((e) => join(initPath, e)))
          } else {
            await rmdir(initPath)
            dirStack.pop()
          }
        } else if (fileStat.isFile()) {
          await unlink(initPath)
          dirStack.pop()
        }
      }
    }
  }
}

export default defineConfig(async (/* commandLineArgs */) => {
  // 每次构建前先删除上一次的产物
  await removeDir('es')
  // 生成两个产物 一个esmodule模块 一个umd通用模块
  return [
    {
      input: 'src/App.tsx', // 指定入口文件
      treeshake: true, // 开启treeshaking
      external: ['react', 'react-dom', 'antd', '@icon-park/react', 'react-rnd'], //F 第三方库使用外部依赖
      output: {
        file: "es/index.js",
        format: 'esm', // 构建产物的模块化类型
        // 指定被排除掉的外部依赖在全局对象上的key
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM'
        }
      },
      plugins: commonPlugins,

    }
  ] as RollupOptions[]
})
